#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <errno.h>
#include <strings.h>
#include <signal.h>
#include <unistd.h>



#define MSG_FILE "./msgfile"

#define MSG_SIZE 1024
int msgid=-1;
struct msgbuf
{
	long mtype;         /* 放消息编号，必须 > 0 */
	char mtext[MSG_SIZE];  /* 消息内容（消息正文） */
};	


void print_err(char *estr){
	perror(estr);
	exit(-1);

}
int create_or_get_msgque(void){
	int msgid=-1;
	key_t key=-1;
	int fd=0;
	//创建一个消息队列专用的文件供ftok用 必须可读写
	fd=open(MSG_FILE,O_RDWR|O_CREAT,0664);
	if(fd ==-1) print_err("open fail");

	//利用存在的文件路径名和8位整型数，计算出key
	key= ftok(MSG_FILE,'b');
	if(key == -1) print_err("ftok fail");

	//利用key创建，或者获取消息队列
	msgid= msgget(key, 0664|IPC_CREAT);
	if(msgid == -1) print_err("msgget fail");

	return msgid;
}
void sig_fun(int signum){
	msgctl(msgid, IPC_RMID, NULL);
	unlink(MSG_FILE);
	exit(-1);
}


int main(int argc, char const *argv[])
{
	
	int ret =-1;

	long recv_msgtype =0;
	if(argc != 2){
		printf(" need msgtype\n");
		exit(-1);
	}
	recv_msgtype = atoi(argv[1]); //类型转换  数字字符串转换成整型数的
	printf("----------my_recv_msgtype=%d----------------\n",recv_msgtype );

	msgid =create_or_get_msgque();
	ret =fork();
	
	if(ret >0){
		signal(SIGINT,sig_fun);
		struct msgbuf msg_buf={0};
		while(1){
			//封装消息包
			bzero(&msg_buf,sizeof(msg_buf));
			scanf("%s",msg_buf.mtext);
			
			printf("please intput sendtotype\n"); //要发送给的编号
			scanf("%d",&msg_buf.mtype);
			
			//发送消息包
			msgsnd(msgid,&msg_buf,MSG_SIZE,0);
		}

	}else if(ret ==0){
		struct msgbuf msg_buf={0};
		int ret =0;
		while(1){
			bzero(&msg_buf,sizeof(msg_buf));
			ret =msgrcv(msgid,&msg_buf,MSG_SIZE,recv_msgtype,0);
			if(ret >0){
				printf("recv:%s\n",msg_buf.mtext );
			}
		}
	}else{
		print_err("fork err");
	}

	return 0;
}



